﻿using DirectShowLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace VirtualCamera
{
    public class VirtualCamera
    {
        private VCamRendererLib.IVCamRenderer m_vcam;                         // VCam instance
        private IBaseFilter m_vcam_filter;                  // VCam Renderer DirectShow Filter
        private Timer timer;

        public VirtualCamera() {
            Guid guid_vcam = new Guid("{3D2F839E-1186-4FCE-B772-B61FAE1ACED7}");
            try
            {
                m_vcam_filter = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(guid_vcam));
                m_vcam = (VCamRendererLib.IVCamRenderer)m_vcam_filter;
                m_vcam.SetOutputFormat(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, 25);
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                //MessageBox.Show("VCam Renderer Filter not registered!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            catch (InvalidCastException)
            {
                //MessageBox.Show("VCam Driver not installed!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            catch (Exception) {
                return;
            }

            timer = new Timer();
            timer.Interval = 50;
            timer.Tick += Timer_Tick;
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            int x = 0;
            int y = 0;
            int w = Screen.PrimaryScreen.Bounds.Width;
            int h = Screen.PrimaryScreen.Bounds.Height;

            if (m_vcam != null)
            {
                m_vcam.CaptureScreen(x, y, w, h);
            }
        }

        public void StartCaptureScreen() {
            if (timer != null)
            {
                timer.Start();
            }
        }

        public void StopCaptureScreen() {
            if (timer != null)
            {
                timer.Stop();
            }
        }
    }
}
